import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    accessToken: localStorage.getItem('accessToken') || '',
    refreshToken: localStorage.getItem('refreshToken') || ''
  },
  mutations: {
    setAccessToken(state, token) {
      state.accessToken = token;
      localStorage.setItem('accessToken', token);
    },
    setRefreshToken(state, token) {
      state.refreshToken = token;
      localStorage.setItem('refreshToken', token);
    },
    clearTokens(state) {
      state.accessToken = '';
      state.refreshToken = '';
      localStorage.removeItem('accessToken');
      localStorage.removeItem('refreshToken');
    }
  },
  actions: {
    async login({ commit }, { username, password }) {
      try {
        const response = await axios.post('http://192.168.33.201:3000/admins/login', { username, password });
        const { accessToken, refreshToken } = response.data;
        commit('setAccessToken', accessToken);
        commit('setRefreshToken', refreshToken);
        return response.data;
      } catch (error) {
        console.error('Login error:', error);
        throw error;
      }
    },
    async refreshAccessToken({ commit, state }) {
      try {
        const response = await axios.post('http://192.168.33.201:3000/admins/refresh-token', {
          refreshToken: state.refreshToken
        });
        const { accessToken } = response.data;
        commit('setAccessToken', accessToken);
        return accessToken;
      } catch (error) {
        commit('clearTokens');
        console.error('Token refresh error:', error);
        throw error;
      }
    },
    updateToken({ commit }, token) {
      commit('setAccessToken', token);
    },
    updateRefreshToken({ commit }, refreshToken) {
      commit('setRefreshToken', refreshToken);
    },
    logout({ commit }) {
      commit('clearTokens');
    }
  },
  getters: {
    accessToken: state => state.accessToken,
    refreshToken: state => state.refreshToken
  }
});
